package cn.xz.diy_service_register.service.impl;

import cn.hutool.http.HttpUtil;
import cn.xz.diy_service_register.ajaxRes.AjaxResult;
import cn.xz.diy_service_register.pojo.RegisterVo;
import cn.xz.diy_service_register.service.IRegisterCenterService;
import com.alibaba.fastjson.JSON;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class RegisterCenterServiceImpl implements IRegisterCenterService {


    private Map<String, Map<String,Object>> hashMap = new HashMap<>();
    private Map<String,Object> serviceList= new HashMap<>();
    private final static String SERVICE_REGISTER = "SERVICE_REGISTER";
    /**
     * 服务注册
     * @param registerVo
     */
    @Override
    public AjaxResult register(RegisterVo registerVo) {

        if (serviceList.size() == 0){
            hashMap.put(SERVICE_REGISTER,serviceList);
        }
        if (serviceList.get(registerVo.getServiceName()) != null){
            System.out.println(serviceList);
            return AjaxResult.me().setMessage("服务续约成功");
        }else {
            serviceList.put(registerVo.getServiceName(),registerVo);

            System.out.println(serviceList);
            return AjaxResult.me().setMessage("服务注册成功");
        }
    }

    /**
     * 服务发现
     * @return
     */
    @Override
    public AjaxResult find() {
        System.out.println("拉取服务列表成功");
        return AjaxResult.me().setData(JSON.toJSONString(serviceList));
    }

    @Scheduled(cron = "0/30 * * * * *")
    public void serviceDelete(){
        Set<Map.Entry<String, Object>> entrySet = serviceList.entrySet();
        for (Map.Entry<String, Object> objectEntry : entrySet) {
            RegisterVo value = (RegisterVo) objectEntry.getValue();
            try {
                String url = "http://127.0.0.1:"+value.getPort();
                HttpUtil.post(url,"");
                System.out.println(value.getServiceName()+"服务存活.......");
            } catch (Exception e) {
                System.out.println(value.getServiceName()+"服务剔除...........");
                serviceList.remove(value.getServiceName());
                throw new RuntimeException(e);
            }

        }
    }


}
